<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      h1 {
        width: 250px;
        margin: 100px auto 50px auto;
      }

      .item {
        width: 500px;
        height: 50px;
        margin: 0 auto;
        text-align: center;
        font-size: 30px;
        color: orange;
      }

      strong {
        background-color: orange;
        padding: 0 10px;
        color: #fff;
        border-radius: 4px;
      }
    </style>
  </head>

  <body>
    <h1>距离国庆节,还有</h1>
    <div class="item">
      <p><span class="day">00</span>天</p>
      <strong><span class="hour">00</span>时</strong>
      <strong><span class="min">00</span>分</strong>
      <strong><span class="second">00</span>秒</strong>
    </div>

    <script>
      function getTime(){
      var span = document.querySelectorAll('span')
      var endTime = new Date('2021-10-1 00:00:00');//获取未来时间
      var starTime = new Date();//获取当前时间,
      //获取时间差  两个时间对象相减  得到时间戳 毫秒级
      var stemp = endTime - starTime;
      console.log(stemp);
      //先算一天有多少毫秒
      var ms_day = 24*60*60*1000;
      //一小时有多少毫秒
      var ms_hours = 60*60*1000;
      //一分钟有多少毫秒
      var ms_min = 60*1000;
      //1s=1000ms
      //天数
      var day = Math.floor(stemp/ms_day)
      //不满一天
      var hours =Math.floor((stemp%ms_day)/ms_hours);
      //不满一小时
      var minute =  Math.floor((stemp%ms_hours)/ms_min);
      //不足一分钟
      var sec = Math.floor((stemp%ms_min)/1000)
     
      span[0].innerText = day;
      span[1].innerText = stat(hours);
      span[2].innerText = stat(minute);
      span[3].innerText = stat(sec);
      if(day==0&&hours==0&&minute==0&&sec==0){
        clearInterval(timer);
      }
      }
      var timer = setInterval(getTime,1000);

      // 格式化方法
      function stat(time){
       return time>9? time:'0'+time;
      }
</script>
  </body>
</html>
